package cn.ccew.sys.web.role;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ccew.sys.model.SysResources;
import cn.ccew.sys.model.SysRole;
import cn.ccew.sys.web.SysBaseController;

@Controller
public class RoleController extends SysBaseController {
	/**
	 * 分页加载
	 * 
	 * @param rootMenuCode
	 * @param start
	 * @param limit
	 * @throws Exception
	 */
	@RequestMapping("role_loadRoleList.wb")
	public void role_loadRoleList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Criteria criteria = this.createCriteria(SysRole.class);
		String[] excludes = new String[] { "createTime", "lastModifyTime" };
		responseListJSON(criteria, request, response, excludes);
	}

	/**
	 * 角色下拉列表加载
	 * 
	 * @param rootMenuCode
	 * @param start
	 * @param limit
	 * @throws Exception
	 */
	@RequestMapping("role_loadRoleListComboBox.wb")
	public void role_loadRoleListComboBox(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Criteria criteria = this.createCriteria(SysRole.class);
		criteria.addOrder(Order.desc("lastModifyTime"));
		List<SysRole> sList = criteria.list();
		List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
		for (SysRole rs : sList) {
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("fid", rs.getId());
			map.put("fname", rs.getRoleName());
			list.add(map);
		}
		String listJson = JSONSerializer.toJSON(list).toString();

		writerTo(response, "{totalProperty:" + sList.size() + ",data:" + listJson + "}");
	}

	/**
	 * 加载一条记录，用于显示修改
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("role_loadRole.wb")
	public void role_loadRole(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysRole org = baseService.findById(id, SysRole.class);
		if (org.getRoleLayer() == 1) {
			throw new Exception();
		}
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("id", org.getId());
			map.put("roleName", org.getRoleName());
			map.put("roleDescription", org.getRoleDescription());
			responseListJSON(response, map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 修改一条记录 id存在为修改，否则创建
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("role_saveRole.wb")
	public void role_saveRole(@ModelAttribute() SysRole role, HttpServletRequest request, HttpServletResponse response) throws Exception {

		try {
			if (StringUtils.isEmpty(role.getId())) {
				List<SysRole> list = baseService.findListByProperty("roleName", role.getRoleName(), SysRole.class);
				if (list.size() > 0) {
					writerFailure(response, "保存失败,登录名已存在，请重新输入");
					return;
				}
			}
			baseService.saveOrUpdate(role);
			writerSuccess(response, "保存成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			writerFailure(response, "保存失败");
			e.printStackTrace();
		}

	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("role_removeRole.wb")
	public void role_removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysRole org = null;
		if (isParameterExist(request, "id")) {
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				org = baseService.findById(id, SysRole.class);
			}
		}
		if (null == org) {
			writerFailure(response, "删除失败，没有找个记录");
			return;
		}
		if (org.getRoleLayer() > 0) {
			writerFailure(response, "删除失败，超级管理员不能编辑或删除");
			return;
		}
		try {
			baseService.delete(org.getId(), SysRole.class);
			writerSuccess(response, "删除成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writerFailure(response, "删除失败，未知原因");
		}

	}

	/**
	 * 修改一条记录 id存在为修改，否则创建
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("role_saveSourse.wb")
	public void role_saveSourse(String id, String rids, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			SysRole sr = baseService.findById(id, SysRole.class);
			if (sr.getRoleLayer() == 1) {
				writerFailure(response, "保存失败,超级管理员权限不能编辑");
				return;
			}
			Set<SysResources> resourcesSet = new HashSet<SysResources>();
			if (StringUtils.isNotEmpty(rids)) {
				if (rids.contains(",")) {
					String[] rr = rids.split(",");
					for (String sid : rr) {
						if (StringUtils.isEmpty(sid)) {
							continue;
						}
						SysResources resour = baseService.findById(sid, SysResources.class);
						if (null != resour) {
							resourcesSet.add(resour);
						}

					}
				}

			}
			if (null == sr) {
				writerFailure(response, "保存失败,参数不正确");
			} else {
				sr.setResources(resourcesSet);
				baseService.saveOrUpdate(sr);
				writerSuccess(response, "保存成功");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			writerFailure(response, "保存失败");
			e.printStackTrace();
		}

	}

	private SysRole currentRole;

	/**
	 * 
	 * @param rootMenuCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("role_loadSourse.wb")
	public void role_loadSourse(String rid, HttpServletRequest reques, HttpServletResponse response) throws Exception {
		currentRole = baseService.findById(rid, SysRole.class);

		if (null == currentRole) {
			writerTo(response, "");
			return;
		}
		Criteria criteria = baseService.createCriteria(SysResources.class);
		criteria.add(Restrictions.isNull("parent"));
		criteria.addOrder(Order.asc("priority"));
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<SysResources> rootList = criteria.list();

		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		config.registerJsonValueProcessor(Long.class, new LongValueProcessor());
		config.registerJsonValueProcessor(int.class, new LongValueProcessor());
		config.registerJsonValueProcessor(Timestamp.class, new TimestampValueProcessor());
		config.registerJsonValueProcessor(SysResources.class, new SysResourcesValueProcessor());

		String[] excludes = new String[] { "parent", "rsName", "expandlist", "createTime", "lastModifyTime", "priority" };
		config.setExcludes(excludes);

		String listJson = "";
		try {
			listJson = JSONSerializer.toJSON(rootList, config).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		writerTo(response, listJson);
	}

	/**
	 * 把资源 对象封装成菜单对象
	 * 
	 * @param source
	 * @return
	 */
	private Map<String, Object> getMapObj(SysResources source) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", source.getId());
		map.put("text", source.getRsName());
		map.put("leaf", source.getLeaf());
		map.put("checked", false);

		map.put("priority", source.getPriority());
		map.put("rsCustomMark", source.getRsCustomMark());
		map.put("functionName", source.getRsFunctionName());
		map.put("rsFunctionJsPath", source.getRsFunctionJsPath());
		if (!source.getLeaf()) {
			List<Map<String, Object>> childs = new ArrayList<Map<String, Object>>();
			for (SysResources s : source.getChildren()) {
				childs.add(getMapObj(s));
			}
			map.put("children", childs);
		}
		try {
			if (currentRole.getRoleLayer() == 1) {
				map.put("checked", true);
			} else if (currentRole.getResources().contains(source)) {
				map.put("checked", true);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	class LongValueProcessor implements JsonValueProcessor {

		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		private Object process(Object value) {

			return value.toString();
		}
	}

	class TimestampValueProcessor implements JsonValueProcessor {

		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		private Object process(Object value) {
			Timestamp obj = (Timestamp) value;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(obj);
		}
	}

	class SysResourcesValueProcessor implements JsonValueProcessor {

		@Override
		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		/**
		 * 处理单个Date对象
		 */
		@Override
		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		private Object process(Object value) {
			SysResources sys = (SysResources) value;
			return JSONObject.fromObject(getMapObj(sys));
		}
	}
}
